//! 回写响应事件驱动器演示
//! 
//! 展示如何使用响应回写驱动器处理存储层操作完成后的响应

use std::sync::{Arc, atomic::{AtomicU64, Ordering}};
use std::time::{Duration, Instant};
use std::thread;

use redis_rs2::event::{
    ResponseWritebackDriver, 
    ResponseEvent,
    NetworkCallback,
    ConnectionId,
    RequestId,
};
use redis_rs2::storage::CommandResult;

fn main() {
    println!("🎯 Redis-rs2 回写响应事件驱动器演示");
    println!("{}", "=".repeat(60));
    
    // 1. 创建响应回写驱动器
    println!("\n📋 1. 创建响应回写驱动器");
    let mut driver = ResponseWritebackDriver::new("main-response-driver", 10000);
    
    // 2. 设置网络回调（模拟网络层）
    println!("\n🌐 2. 设置网络回调");
    
    let callback_counter = Arc::new(AtomicU64::new(0));
    let callback_counter_clone = Arc::clone(&callback_counter);
    
    let network_callback: NetworkCallback = Arc::new(move |conn_id, req_id, response_data| {
        let count = callback_counter_clone.fetch_add(1, Ordering::SeqCst);
        
        // 模拟网络回写延迟
        thread::sleep(Duration::from_micros(50));
        
        println!(
            "  📤 [网络回写 #{}] 连接:{} 请求:{} 响应:{}", 
            count + 1, conn_id, req_id, response_data.trim()
        );
    });
    
    driver.set_network_callback(network_callback);
    
    // 3. 启动驱动器
    println!("\n🚀 3. 启动驱动器");
    if let Err(e) = driver.start() {
        eprintln!("❌ 启动失败: {}", e);
        return;
    }
    
    // 4. 模拟存储层操作并提交响应
    println!("\n💾 4. 模拟存储层操作");
    
    let start_time = Instant::now();
    
    // 模拟各种命令的响应
    let test_cases = vec![
        (1, 101, CommandResult::String("Alice".to_string()), "GET"),
        (1, 102, CommandResult::Ok, "SET"),
        (2, 201, CommandResult::Integer(42), "INCR"),
        (2, 202, CommandResult::Boolean(true), "EXISTS"),
        (3, 301, CommandResult::Null, "GET"),
        (3, 302, CommandResult::Array(vec![
            CommandResult::String("field1".to_string()),
            CommandResult::String("value1".to_string()),
        ]), "HGETALL"),
        (1, 103, CommandResult::Error("Key not found".to_string()), "GET"),
    ];
    
    for (conn_id, req_id, result, cmd_name) in test_cases {
        let cmd_start_time = current_timestamp_millis();
        
        println!("  📨 提交响应: 连接:{} 请求:{} 命令:{}", conn_id, req_id, cmd_name);
        
        if let Err(e) = driver.submit_command_result(
            conn_id, 
            req_id, 
            result, 
            cmd_name.to_string(), 
            cmd_start_time
        ) {
            eprintln!("    ❌ 提交失败: {}", e);
        }
        
        // 模拟命令处理间隔
        thread::sleep(Duration::from_millis(100));
    }
    
    // 5. 高并发测试
    println!("\n⚡ 5. 高并发响应提交测试");
    
    let concurrent_count = 1000;
    let batch_start = Instant::now();
    
    // 使用多个线程并发提交响应
    let handles: Vec<_> = (0..4).map(|thread_id| {
        let driver_queue = driver.get_queue();
        
        thread::spawn(move || {
            for i in 0..concurrent_count / 4 {
                let conn_id = (thread_id * 1000 + i) as ConnectionId;
                let req_id = i as RequestId;
                
                let response_event = ResponseEvent::new(
                    conn_id,
                    req_id,
                    CommandResult::String(format!("batch_result_{}", i)),
                    "BATCH_GET".to_string(),
                    current_timestamp_millis(),
                );
                
                // 创建事件包装器并直接推送到队列
                let metadata = redis_rs2::event::EventMetadata::new("response")
                    .with_priority(redis_rs2::event::Priority::Normal)
                    .with_source("batch-test");
                
                let event_wrapper = redis_rs2::event::Event::with_metadata(metadata, response_event);
                
                if let Err(_) = driver_queue.enqueue(event_wrapper) {
                    eprintln!("  ❌ 批量提交失败: 队列已满");
                    break;
                }
            }
            
            println!("  ✅ 线程 {} 完成批量提交", thread_id);
        })
    }).collect();
    
    // 等待所有线程完成
    for handle in handles {
        handle.join().unwrap();
    }
    
    let batch_duration = batch_start.elapsed();
    println!("  📊 批量提交完成: {}个响应，耗时: {:?}", concurrent_count, batch_duration);
    
    // 6. 等待处理完成并查看统计
    println!("\n⏱️ 6. 等待处理完成");
    
    let mut last_processed = 0;
    for _ in 0..30 { // 最多等待30秒
        let stats = driver.get_stats();
        let queue_size = driver.queue_size();
        
        if stats.total_responses_processed != last_processed {
            println!(
                "  📈 已处理: {} 队列大小: {} 成功率: {:.1}%",
                stats.total_responses_processed,
                queue_size,
                if stats.total_responses_processed > 0 {
                    stats.successful_writebacks as f64 / stats.total_responses_processed as f64 * 100.0
                } else { 0.0 }
            );
            last_processed = stats.total_responses_processed;
        }
        
        if queue_size == 0 && stats.total_responses_processed > 0 {
            break;
        }
        
        thread::sleep(Duration::from_secs(1));
    }
    
    // 7. 打印详细统计信息
    println!("\n📊 7. 详细统计信息");
    driver.print_stats();
    
    // 8. 验证网络回调调用次数
    let total_callbacks = callback_counter.load(Ordering::SeqCst);
    println!("\n✅ 网络回调总调用次数: {}", total_callbacks);
    
    // 9. 停止驱动器
    println!("\n🛑 9. 停止驱动器");
    if let Err(e) = driver.stop() {
        eprintln!("❌ 停止失败: {}", e);
    }
    
    let total_duration = start_time.elapsed();
    println!("\n🎉 演示完成！");
    println!("  总运行时间: {:?}", total_duration);
    println!("  平均吞吐量: {:.0} 响应/秒", 
        total_callbacks as f64 / total_duration.as_secs_f64());
    
    println!("\n💡 总结:");
    println!("  ✅ 回写响应事件驱动器运行正常");
    println!("  ✅ 支持高并发响应处理");
    println!("  ✅ 网络回调机制工作正常");
    println!("  ✅ 统计信息收集完整");
    println!("  ✅ 为网络层集成做好准备");
}

/// 获取当前时间戳（毫秒）
fn current_timestamp_millis() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}